#include <string>
#include <sstream>

#include "utility.h"
#include "MyLog.h"
#include "../common.h"

string utility::string2upper(string str)
{
	string strReturn;
	int i,j;
	j = str.length();
	for (i=0;i<j;i++)
	{
		strReturn += toupper(str[i]);
	}
	return strReturn;
}

string utility::string2lower(string str)
{
	string strReturn;
	int i,j;
	j = str.length();
	for (i=0;i<j;i++)
	{
		strReturn += tolower(str[i]);
	}
	return strReturn;
}


void utility::replace(string *strRtn, char chr)
{
	utility::replace(strRtn, chr, ' ');
}

void utility::replace(string *strRtn, char chrFrom, char chrTo)
{
    int i ;
    int istrlen = (*strRtn).length();
    for (i=0;i<istrlen;i++)
    {
        if ((*strRtn)[i] == chrFrom)
            (*strRtn)[i] = chrTo;
    }
}

void utility::replace(string *strRtn, string strFrom, string strTo)
{
	(*strRtn).replace((*strRtn).find(strFrom),strFrom.length(),strTo);
}

string utility::trim(string strRtn)
{
    replace(&strRtn);
    int pos;
	//check is space string

    //left trim
    pos = strRtn.find_first_not_of(' ');
    if (pos == -1) return "";
    if (pos > 0)
		strRtn = strRtn.substr(pos,strRtn.length());

    //right trim
    pos = strRtn.find_last_not_of(' ');
    if (pos >0)
		strRtn = strRtn.substr(0,pos+1);

    return strRtn;
}

string utility::int2string(int x)
{
	ostringstream _r;
	_r << x;
	return _r.str();
}

string utility::long2string(long x)
{
	ostringstream r;
	r << x;
	return r.str();
}


int utility::string2int(string x)
{
	return atoi(x.c_str());
}

void utility::splistString(string str,char chr,string *strKey,string *strValue, bool upperKey)
{
    int t;
    t = str.find(chr);
    if (t != -1)
    {
        (*strKey) = str.substr(0,t);
        (*strValue) = str.substr(t+1,str.length());
        (*strKey) = trim((*strKey));
        if (upperKey)(*strKey) = string2upper((*strKey));
        (*strValue) = trim((*strValue));
    }else{
        (*strKey) = "";
        (*strValue) = trim(str);
    }
};

string utility::getRandGuestName()
{
	ostringstream r;
	srand(time(NULL));
	r << (rand() % 1000 ) + 1;
	return ((string)"guest").append(r.str());
}

string utility::getRandGuestName(int iMax)
{
	ostringstream r;
	srand(time(NULL));
	r << (rand() % iMax ) + 1;
	return r.str();
}
